package de.slothsoft.commons;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AudioHandler {

	private byte[] buffer;

	public AudioHandler() {
		this(5000);
	}

	public AudioHandler(int bufferSize) {
		this.buffer = new byte[bufferSize];
	}

	public void play(String filePath) throws LineUnavailableException,
			IOException, UnsupportedAudioFileException {
		File datei = new File(filePath);
		play(AudioSystem.getAudioInputStream(datei));
	}

	public void play(InputStream inputStream) throws LineUnavailableException,
			IOException, UnsupportedAudioFileException {
		play(AudioSystem.getAudioInputStream(inputStream));
	}

	public void play(AudioInputStream inStream)
			throws LineUnavailableException, IOException {
		AudioFormat format = inStream.getFormat();
		AudioInputStream audioStream = inStream;

		if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
			AudioFormat newFormat = new AudioFormat(
					AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(),
					2 * format.getSampleSizeInBits(), format.getChannels(),
					2 * format.getFrameSize(), format.getFrameRate(), true);
			audioStream = AudioSystem.getAudioInputStream(newFormat, inStream);
			format = newFormat;
		}

		SourceDataLine line = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

		line = (SourceDataLine) AudioSystem.getLine(info);
		line.open(format);
		line.start();

		int num = 0;

		try {
			while (num != -1) {
				num = audioStream.read(this.buffer, 0, this.buffer.length);
				if (num >= 0) {
					line.write(this.buffer, 0, num);
				}
			}
		} finally {
			line.drain();
			line.close();
		}
	}

}
